package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Report;
import priv.mill.server.ReportService;

@Controller
@RequestMapping("Report")
public class ReportController {

	@Autowired
	private ReportService reportService;

	private static final Logger logger = Logger.getLogger(ReportController.class);

	@RequestMapping("getReportById")
	@ResponseBody
	public RetenObj getReportById(@RequestParam("ReportId") Integer reportId) {
		try {
			return warpData(reportService.getReportById(reportId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getReportByEntry")
	@ResponseBody
	public RetenObj getReportByEntry(Report report) {
		try {
			return warpData(reportService.getReportByEntry(report), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getReportsByPage")
	@ResponseBody
	public RetenObj getReportsByPage(Report report) {
		try {
			return warpData(reportService.getReportsByPage(report), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateReport")
	@ResponseBody
	public RetenObj updateReport(Report report) {
		try {
			int result = reportService.updateReport(report);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertReport")
	@ResponseBody
	public RetenObj insertReport(Report report) {
		try {
			int result = reportService.insertReport(report);
			if (result > 0)
				return warpData(report.getReportId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteReport")
	
	@ResponseBody
	public RetenObj deleteReport(Integer reportId) {
		try {
			int result = reportService.deleteReport(reportId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
